using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using Qreed.Xna.Font;

namespace Qreed.Xna.SandBox
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            graphics.PreferredBackBufferWidth = 1680;
            graphics.PreferredBackBufferHeight = 1050;

            Content.RootDirectory = "Content";

            this.IsMouseVisible = true;
        }

        private InputStateComponent _inputState;
        private CameraComponent _camera;
        private FrameRateComponent _frameRate;
        private VectorFont _vectorFont;
        private FilledFont _filledFont;
        private ExtrudedFont _extrudedFont;
        private BasicTransformEffect _fontEffect;
        private VectorTextComponent _vectorText;
        private AxisComponent _axis;

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            _inputState = new InputStateComponent(this);
            Components.Add(_inputState);

            _camera = new CameraComponent(this);
            _camera.Position = new Vector3(10.0f, 10.0f, 20.0f);
            _camera.LookAt(Vector3.Zero);
            //_camera.LookAt(new Vector3(40.0f, 0.0f, -5.0f));

            Components.Add(_camera);

            _vectorText = new VectorTextComponent(this);
            Components.Add(_vectorText);

            _frameRate = new FrameRateComponent(this);
            Components.Add(_frameRate);
            
            GridComponent grid = new GridComponent(this, _camera);
            Components.Add(grid);

            _axis = new AxisComponent(this, _camera);
            Components.Add(_axis);

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            
            _vectorFont = Content.Load<VectorFont>("Fonts/VectorFont");
            
            _filledFont = new FilledFont();
            _filledFont.LoadContent(GraphicsDevice, _vectorFont);

            _extrudedFont = new ExtrudedFont(10.0f);
            _extrudedFont.LoadContent(GraphicsDevice, _vectorFont);

            //_extrudedFont = new ExtrudedFont(GraphicsDevice, _vectorFont, 20.0f);

            _fontEffect = new BasicTransformEffect(GraphicsDevice, null);
            _fontEffect.EnableDefaultLighting();

            _vectorText.VectorFont = _filledFont;
            _vectorText.Text = "@";
            _vectorText.TransformEffect = _fontEffect;

            base.LoadContent();
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        private bool _isCulling = true;

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            
            if (_inputState.IsNewKeyDown(Keys.F1))
            {
                _frameRate.Visible = !_frameRate.Visible;
            }

            if (_inputState.IsNewKeyDown(Keys.F2))
            {
                GraphicsDevice.RenderState.FillMode = GraphicsDevice.RenderState.FillMode == FillMode.WireFrame ? FillMode.Solid : FillMode.WireFrame;
            }

            if (_inputState.IsNewKeyDown(Keys.F3))
            {
                _isCulling = !_isCulling;
            }

            if (_inputState.IsNewKeyDown(Keys.Escape))
                Exit();

            float rotateX = 0.0f;
            float rotateY = 0.0f;

            if (_inputState.IsKeyDown(Keys.Left))
                rotateY -= 1.0f * (float)gameTime.ElapsedGameTime.TotalMilliseconds * 0.003f;
            if (_inputState.IsKeyDown(Keys.Right))
                rotateY += 1.0f * (float)gameTime.ElapsedGameTime.TotalMilliseconds * 0.003f;

            if (_inputState.IsKeyDown(Keys.Up))
                rotateX -= 1.0f * (float)gameTime.ElapsedGameTime.TotalMilliseconds * 0.003f;
            if (_inputState.IsKeyDown(Keys.Down))
                rotateX += 1.0f * (float)gameTime.ElapsedGameTime.TotalMilliseconds * 0.003f;

            if (_inputState.CurrentMouseState.RightButton == ButtonState.Pressed)
            {
                rotateY -= (float)(_inputState.LastMouseState.X - _inputState.CurrentMouseState.X) * 0.01f;
                rotateX -= (float)(_inputState.LastMouseState.Y - _inputState.CurrentMouseState.Y) * 0.01f;

                //System.Diagnostics.Debug.WriteLine("Y: " + _inputState.CurrentMouseState.Y);
                //System.Diagnostics.Debug.WriteLine("X: " + _inputState.CurrentMouseState.X);
                //Mouse.SetPosition(_camera.ViewPort.Width / 2, _camera.ViewPort.Height / 2);
            }

            _camera.Rotation += new Vector3(rotateX, rotateY, 0.0f);

            float xMove = 0.0f;
            float forward = 0.0f;

            if (_inputState.IsKeyDown(Keys.A))
                xMove -= 1.0f * (float)gameTime.ElapsedGameTime.TotalMilliseconds * 0.01f;
            if (_inputState.IsKeyDown(Keys.D))
                xMove += 1.0f * (float)gameTime.ElapsedGameTime.TotalMilliseconds * 0.01f;
            if (_inputState.IsKeyDown(Keys.S))
                forward -= 1.0f * (float)gameTime.ElapsedGameTime.TotalMilliseconds * 0.01f;
            if (_inputState.IsKeyDown(Keys.W))
                forward += 1.0f * (float)gameTime.ElapsedGameTime.TotalMilliseconds * 0.01f;

            _camera.Position += _camera.Right * xMove;
            _camera.Position += _camera.Forward * forward;
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            //GraphicsDevice.Clear(ClearOptions.DepthBuffer|ClearOptions.Target, Color.CornflowerBlue, 1.0f, 0);

            GraphicsDevice.Clear(Color.Gray);

            GraphicsDevice.RenderState.DepthBufferEnable = true;
            GraphicsDevice.RenderState.CullMode = _isCulling ? CullMode.CullCounterClockwiseFace : CullMode.None;

            _fontEffect.View = _camera.View;
            _fontEffect.Projection = _camera.Projection;
            
            /*    
            for (int i = 0; i < _vectorText.Text.Length; i++)
            {
                _fontEffect.World = _vectorText.Transforms[i];

                _fontEffect.Begin();

                foreach (EffectPass pass in _fontEffect.CurrentTechnique.Passes)
                {
                    pass.Begin();

                    ((FilledFontCharacter)_vectorText.Characters[i]).Draw();

                    pass.End();
                }

                _fontEffect.End();
            }*/

            base.Draw(gameTime);
        }
    }
}
